package com.funtask.fun.controller;

import cn.hutool.core.util.StrUtil;
import com.funtask.fun.common.CommonResult;
import com.funtask.fun.components.MyUserDetails;
import com.funtask.fun.demos.web.User;
import com.funtask.fun.entity.UserInfo;
import com.funtask.fun.enums.LoginType;
import com.funtask.fun.manager.UserManager;
import com.funtask.fun.service.IUserInfoService;
import com.funtask.fun.utils.JwtTokenUtil;
import com.funtask.fun.vo.AccessTokenVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zhangqi
 * @date 2024/1/2
 * @time 20:55
 * @description
 */
@RestController
@Slf4j
public class AuthController {
    @Autowired
    private UserManager userManager;
    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @PostMapping("/doLogin/{loginType}")
    public CommonResult<AccessTokenVo> login(@PathVariable String loginType, @RequestBody User user) {
        log.info("similation login user:{}", user);
        UserInfo userInfo = null;
        if (StrUtil.isNotBlank(loginType)) {
            if (loginType.equals(LoginType.CODE.getCode())) {
                //
                log.info("验证码登陆");
            } else if (loginType.equals(LoginType.PASS.getCode())) {
                userInfo = userManager.getByUserName(user.getUsername());
                if (userInfo == null) {
                    log.info("userInfo==null");
                    throw new BadCredentialsException("用户名或密码不对！");
                }
                if (!passwordEncoder.matches(user.getPassword(), userInfo.getPassword())) {
                    throw new BadCredentialsException("用户名或密码不对！");
                }
            }
        } else {
            throw new IllegalArgumentException("登陆type路径参数必须要传");
        }
        MyUserDetails userDetails = MyUserDetails.builder().userInfo(userInfo).build();
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        String token = jwtTokenUtil.generateToken(userDetails.getUserId());
        AccessTokenVo accessTokenVo = AccessTokenVo.builder().token(token).tokenHeader(tokenHead)
                .expiresIn(jwtTokenUtil.getExpiration()).build();
        return CommonResult.success(accessTokenVo);
    }

    @PostMapping("/register")
    public CommonResult register(@RequestBody UserInfo userInfo) throws Exception {
        // 默认显示这行的值，后期再根据需要修改
        Integer createCode = null;
        try {
            createCode = userInfoService.createUserInfo(userInfo);
            return CommonResult.success(createCode, "注册成功");
        } catch (Exception e) {
            return CommonResult.failed(e.getMessage());
        }

    }

    @PostMapping("/logout")
    public CommonResult<Boolean> logout() {
//        if("Y".equals(RedisCacheUtil.getString(CurrentUserUtil.getXNumber()))){
//            RedisCacheUtil.setString(CurrentUserUtil.getXNumber(), "N");
//            MemberDo memberDo = new MemberDo();
//            memberDo.setXNumber(Long.parseLong(CurrentUserUtil.getXNumber()));
//            memberDo.setOnlineStatus(0);
//            memberService.update(memberDo);
        return CommonResult.success(true,"退出成功");
//        }else{
//            return CommonResult.failed("退出失败");
//        }
    }
}
